package study.ttl.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.ttl.entity.Goods;
import study.ttl.mapper.GoodsMapper;
import study.ttl.service.GoodsService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;



    /**
     * 添加商品
     * @param goods
     */
    @Override
    public void add(Goods goods) {
        goods.setDate(DateUtil.today());
        goodsMapper.insert(goods);
    }

    /**
     * 根据id删除商品
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        goodsMapper.deleteById(id);
    }


    /**
     * 修改商品信息
     * @param goods
     */
    @Override
    public void update(Goods goods) {
        goodsMapper.updateById(goods);
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @Override
    public Goods selectById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        return goods;
    }

    /**
     * 查询所有商品
     * @return
     */
    @Override
    public List<Goods> selectAll(Goods goods) {
        List<Goods> userList = goodsMapper.selectAll(goods);
        return userList;
    }

    /**
     * 分页查询商品
     * @param pageNum
     * @param pageSize
     * @param goods
     * @return
     */
    @Override
    public PageInfo<Goods> selectPage(Integer pageNum, Integer pageSize, Goods goods) throws ParseException {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.selectAll(goods);
        extracted(goodsList);
        return PageInfo.of(goodsList);
    }

    /**
     * 批量删除商品
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        goodsMapper.deleteBatch(ids);
    }

    /**
     * 秒杀商品（限量2个）
     * @param goods
     * @return
     */
    @Override
    public List<Goods> selectFlash(Goods goods) throws ParseException {
        List<Goods> goodsList = goodsMapper.selectAll(goods);
        extracted(goodsList);
        return goodsList.size() > 2 ? goodsList.subList(0, 2) : goodsList;
    }

    private static void extracted(List<Goods> goodsList) throws ParseException {
        for (Goods dbGoods : goodsList) {
            if (dbGoods.getHasFlash() && ObjectUtil.isNotEmpty(dbGoods.getFlashTime())) {
                long now = System.currentTimeMillis();
                Date end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dbGoods.getFlashTime());
                long gap = (end.getTime() - now) / 1000;
                dbGoods.setMaxTime(gap);
            }

        }
    }


}
